package classes.io;

import org.junit.Test;

import java.io.*;

/**
 * 数据流
 */
public class DataStream {
    /**
     * 输出文件
     */
    @Test
    public void test() {
        DataOutputStream dataOutputStream = null;
        try {
            dataOutputStream = new DataOutputStream(new FileOutputStream("./src/classes/io/DataOutputStream.dat"));// 数据流输出
            dataOutputStream.writeBoolean(true);
            dataOutputStream.writeUTF("你好世界");
            dataOutputStream.writeDouble(1.2435454525);
            System.out.println("写入文件成功");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dataOutputStream != null) {
                try {
                    dataOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 输入文件
     */
    @Test
    public void test2() {
        DataInputStream dataInputStream = null;
        try {
            dataInputStream = new DataInputStream(new FileInputStream("./src/classes/io/DataOutputStream.dat"));
            System.out.println(dataInputStream.readBoolean());  // 逐个读入
            System.out.println(dataInputStream.readUTF());
            System.out.println(dataInputStream.readDouble());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(dataInputStream != null){
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
